<template>
  <div class="scheduling">
    <!--左边二级侧边栏-->
    <div class="content-left"></div>
    <!--右边内容-->
    <div class="content-right">
      <div class="content-top">
        <span>排班</span>
      </div>
      <div class="content-content">
        <div class="content-head flex flex-between">
          <div class="input-item fl">
            <span class="span-input fl">
              <el-cascader
                v-model="paramsTmp.selectWorker"
                :options="allWorker"
                :props="{checkStrictly: true}"
                filterable
                placeholder="请选择部门/员工"
                clearable
                @change="FnSelectWorkerChange"
              ></el-cascader>
            </span>
          </div>
          <!-- <div class="input-item fl">
              <span class="span-input fl">
                <el-select v-model="params.classId" placeholder="请选择">
                  <el-option
                    v-for="item in shiftsOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </span>
          </div> -->

          <div class="input-item fl flex flex-y-center">
            <span class="span-title fl">选择日期：</span>
            <span class="span-input fl">
              <el-date-picker
                v-model="paramsTmp.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </span>
          </div>

          <div class="input-item fl">
            <span class="span-input fl">
              <el-button type="primary" @click="FnSchedulingByDay"
                >工作日排班</el-button
              >
              <el-button type="primary" @click="FnSchedulingByClass"
                >班次排班</el-button
              >
              <el-button type="primary" @click="FnSearch">查询</el-button>
            </span>
            <span class="span-input fl">
              <el-button type="primary" @click="FnExport">导出</el-button>
            </span>
          </div>
        </div>
        <div class="content-table">
          <el-table
            v-loading="tableLoading"
            ref="dragTable"
            :data="tableData"
            row-key="id"
            border
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column fixed="left" label="员工" width="150">
              <template slot-scope="scope">
                {{ scope.row['workerNo'] }}
              </template>
            </el-table-column>
            <el-table-column
              v-for="(n1, i1) in columns"
              :key="n1.id"
              :label="n1.label"
              min-width="150"
            >
              <template slot-scope="scope">
                <div
                  class="cursor"
                  @click="FnEdit(n1, scope.row[n1.dataIndex], scope.row)"
                >
                  {{ scope.row[n1.dataIndex] && scope.row[n1.dataIndex].value }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!--各种弹窗-->
    <Vmask :mask="mask" @FnMask="FnMask" />
  </div>
</template>
<script>
import mixins from '@/const/mixins'
import {Class} from '@/const/api'
import Vmask from '@/components/vmask.vue'
import {tempShifts} from '@/const/api'

export default {
  name: 'Scheduling',
  components: {
    Vmask,
  },
  mixins: [mixins],
  data() {
    return {
      params: {
        startDay: null,
        endDay: null,
      },
      columns: [],
      paramsTmp: {
        date: null,
        selectWorker: [],
      },
      tableData: [],
      tableLoading: false,
      allWorker: [],
      shiftsOptions: [],
      OriginShiftsOptions: [],
      mask: {
        id: null,
        title: '',
        showMask: false,
        form: [
          {
            title: '日期',
            width: '',
            type: 'text',
            name: 'day',
            value: '',
            default: '',
            placeholder: '请填写日期',
            disabled: true,
            required: true,
          },
          {
            title: '开始时间',
            width: '',
            type: 'text',
            name: 'startTime',
            value: '',
            default: '',
            placeholder: '请填写开始时间',
            disabled: true,
            required: true,
          },
          {
            title: '结束时间',
            width: '',
            type: 'text',
            name: 'endTime',
            value: '',
            default: '',
            placeholder: '请填写结束时间',
            disabled: true,
            required: true,
          },
          {
            title: '开始时间',
            width: '',
            type: 'date',
            name: 'startDay',
            value: '',
            default: '',
            placeholder: '请开始时间',
            disabled: false,
            required: true,
            hidden: true,
          },
          {
            title: '结束时间',
            width: '',
            type: 'date',
            name: 'endDay',
            value: '',
            default: '',
            placeholder: '请结束时间',
            disabled: false,
            required: true,
            hidden: true,
          },
          {
            title: '选择人员',
            width: '',
            type: 'cascader',
            name: 'selectWorker',
            value: '',
            default: '',
            placeholder: '请选择人员',
            disabled: false,
            required: true,
            hidden: true,
          },
          {
            title: '班次',
            width: '',
            type: 'select',
            name: 'classId',
            value: '',
            default: '',
            placeholder: '请填写班次',
            disabled: false,
            required: true,
          },
        ],
        width: '28%',
        btnLoading: false,
      },
    }
  },
  created() {
    window._this = this
    this.getAllWorker() // 获取所以部门以及员工
    this.getAllShiftsList() // 获取所有班次
  },
  methods: {
    async FnMask(e) {
      console.log(e)
      let type = e.type
      let content = e.content ? JSON.parse(JSON.stringify(e.content)) : false
      let mask = this.mask
      if (type == 'cancel') {
        mask.showMask = false
        this.initMask(mask)
        this.$utils.clearForm(mask.form)
      } else if (type == 'scheduling') {
        this.$utils.maskForm(mask.form).then(async res => {
          mask.btnLoading = true
          res.workerNo = mask.workerNo
          let {state, data, msg} = await this.$axios.$get(
            Class('changeClassOne'),
            {params: res},
          )
          if (state == this.ResCode) {
            this.$Message.success('修改成功')
            setTimeout(() => {
              this.FnSearch()
            }, 100)
          } else {
            this.$Message.success(msg)
          }
          mask.showMask = false
          mask.btnLoading = false
          this.initMask(mask)
          this.$utils.clearForm(mask.form)
        })
      } else if (type == 'schedulingByDay' || type == 'schedulingByClass') {
        this.$utils.maskForm(mask.form).then(async res => {
          mask.btnLoading = true
          let responents
          let workers = []
          let params = JSON.parse(JSON.stringify(res))
          let item = this.OriginShiftsOptions.find((n1, i1) => {
            return n1.id == res.classId
          })
          params.startDay = this.$utils.parseTime(
            new Date(params.startDay),
            '{y}-{m}-{d}',
          )
          params.endDay = this.$utils.parseTime(
            new Date(params.endDay),
            '{y}-{m}-{d}',
          )
          params.startTime = item ? item.startTime : null
          params.endTime = item ? item.endTime : null
          if (res.selectWorker.length == 1) {
            this.allWorker.forEach((n1, i1) => {
              if (
                n1.id == res.selectWorker[0] &&
                n1.children &&
                n1.children.length
              ) {
                n1.children.forEach((n2, i2) => {
                  workers.push(n2.employeeNo)
                })
              }
            })
          } else {
            workers.push(res.selectWorker[1])
          }

          params.employeeNo = workers.join(',')
          delete params.selectWorker

          if (mask.schedulingByDay) {
            responents = await this.$axios.$get(Class('setclassByWorkDay'), {
              params,
            })
          } else {
            responents = await this.$axios.$get(Class('setPeopleBYClass'), {
              params,
            })
          }

          if (responents.state == this.ResCode) {
            mask.schedulingByDay
              ? this.$Message.success('按工作日排班成功')
              : this.$Message.success('按班次排班成功')
          } else {
            this.$Message.error(responents.msg)
          }
          mask.showMask = false
          mask.btnLoading = false
          this.initMask(mask)
          this.$utils.clearForm(mask.form)
        })
      } else if (type == 'cascaderChange') {
        let {data, state, code, msg, count} = await this.$axios.$get(
          Class('selectAllClass'),
          {params: {deptId: content.content.value[0]}},
        )
        if (state == this.ResCode) {
          data &&
            data.length &&
            data.forEach((n1, i1) => {
              n1.label = n1.className
              n1.value = n1.id
            })
          this.mask.classIdOptions = data
          // 强制刷新 dom
          this.mask.form.forEach((n2, i2) => {
            n2.hidden = !n2.hidden
          })
          this.mask.form.forEach((n3, i3) => {
            n3.hidden = !n3.hidden
          })
          // 强制刷新 dom
        }
      } else if (type == 'selectChange') {
        let item = this.shiftsOptions.find((n1, i1) => {
          return n1.id == content.content.value
        })
        mask.form.forEach((n1, i1) => {
          n1.name == 'startTime' && (n1.value = item.startTime)
          n1.name == 'endTime' && (n1.value = item.endTime)
        })
      }
    },
    async FnSearch() {
      let params = JSON.parse(JSON.stringify(this.params))
      let paramsTmp = this.paramsTmp
      let columns = []
      let tableData = []
      let once = false
      let Default = {}
      if (!paramsTmp.date)
        return this.$Message.error('请选择开始日期 跟 结束日期')
      params.startDay = this.$utils.parseTime(paramsTmp.date[0], '{y}-{m}-{d}')
      params.endDay = this.$utils.parseTime(paramsTmp.date[1], '{y}-{m}-{d}')
      paramsTmp.selectWorker.length == 1
        ? ((params.deptId = paramsTmp.selectWorker[0]),
          delete params.employeeNo)
        : ((params.deptId = paramsTmp.selectWorker[0]),
          (params.employeeNo = paramsTmp.selectWorker[1]))
      this.tableLoading = true
      let {state, msg, data} = await this.$axios.$get(Class('selectClass'), {
        params,
      })
      this.tableLoading = false
      if (state == this.ResCode) {
        if (JSON.stringify(data) != '{}') {
          window._data = data
          Default = JSON.parse(JSON.stringify(Default))
          for (let key in data) {
            let obj = {}
            obj.workerNo = key
            obj.row = data[key]
            if (
              data[key] &&
              data[key].length &&
              data[key].length > columns.length
            ) {
              columns = []
              data[key].forEach((n1, i1) => {
                columns.push({
                  label:
                    n1.day +
                    '(' +
                    this.$utils.getDay(new Date(n1.day).getDay()) +
                    ')',
                  dataIndex: 'n' + (i1 + 1),
                })
                Default['n' + (i1 + 1)] = ''
              })
              once = true
            }
            if (data[key] && data[key].length) {
              data[key].forEach((n2, i2) => {
                obj['n' + (i2 + 1)] = {
                  startTime: n2.startTime,
                  endTime: n2.endTime,
                  value: n2.className,
                  classId: Number(n2.classId),
                  day: n2.day,
                }
              })
              tableData.push(obj)
            } else {
              Default = JSON.parse(JSON.stringify(Default))
              Default.workerNo = key
              tableData.push(Default)
            }
          }
          this.columns = columns
          this.tableData = tableData
        }
      } else {
        this.$Message.error(msg)
      }
    },
    FnEdit(col, content, row) {
      let mask = this.mask
      mask.scheduling = true
      mask.showMask = true
      mask.title = '单个修改'
      mask.workerNo = row.workerNo
      mask.form.forEach((n1, i1) => {
        if (
          n1.name != 'startDay' &&
          n1.name != 'selectWorker' &&
          n1.name != 'endDay'
        ) {
          n1.hidden = false
        } else {
          n1.hidden = true
        }
      })
      this.$utils.maskForm(content, mask.form).then(res => {
        mask.form = res
        mask.classIdOptions = this.shiftsOptions
      })
    },
    FnExport() {
      let params = JSON.parse(JSON.stringify(this.params))
      let paramsTmp = this.paramsTmp
      let str = ''
      if (!paramsTmp.date)
        return this.$Message.error('请选择开始日期 跟 结束日期')
      params.startDay = paramsTmp.date
        ? this.$utils.parseTime(paramsTmp.date[0], '{y}-{m}-{d}')
        : ''
      params.endDay = paramsTmp.date
        ? this.$utils.parseTime(paramsTmp.date[1], '{y}-{m}-{d}')
        : ''
      paramsTmp.selectWorker.length == 1
        ? ((params.deptId = paramsTmp.selectWorker[0]),
          delete params.employeeNo)
        : ((params.deptId = paramsTmp.selectWorker[0]),
          (params.employeeNo = paramsTmp.selectWorker[1]))
      Object.keys(params).forEach((n1, i1) => {
        params[n1] && (str += n1 + '=' + params[n1] + '&')
      })
      this.$axios({
        url: 'class/gets',
        method: 'get',
        params: params,
        responseType: 'arraybuffer',
      }).then(res => {
        this.$utils.downBlob(res, '排班')
      })
    },
    FnSchedulingByDay() {
      let mask = this.mask
      mask.showMask = true
      mask.schedulingByDay = true
      mask.title = '按工作日排班'
      mask.selectWorkerOptions = this.allWorker
      mask.form.forEach((n1, i1) => {
        if (n1.name == 'classId' || n1.name == 'selectWorker') {
          n1.hidden = false
        } else {
          n1.hidden = true
        }
      })
      mask.classIdOptions = []
    },
    FnSchedulingByClass() {
      let mask = this.mask
      mask.showMask = true
      mask.schedulingByClass = true
      mask.title = '按班次排班'
      mask.selectWorkerOptions = this.allWorker
      mask.form.forEach((n1, i1) => {
        if (n1.name == 'classId' || n1.name == 'selectWorker') {
          n1.hidden = false
        } else {
          n1.hidden = true
        }
      })
      mask.classIdOptions = []
    },
    initMask(mask) {
      delete mask.id
      delete mask.workerNo
      delete mask.scheduling
      delete mask.schedulingByClass
      delete mask.schedulingByDay
    },
    async FnSelectWorkerChange(e) {
      let {data, state, code, msg, count} = await this.$axios.$get(
        Class('selectAllClassNoStatus'),
      )
      if (state == this.ResCode) {
        data &&
          data.length &&
          data.forEach((n1, i1) => {
            n1.label = n1.className
            n1.value = n1.id
            n1.disabled = !Boolean(n1.enableStatus)
          })
        this.shiftsOptions = data
      }
    },
  },
}
</script>

<style lang="less">
.scheduling {
  .cursor {
    cursor: pointer;
  }
}
</style>
